import React, { createContext, useContext, useReducer, ReactNode, useEffect } from 'react';
import { ChatMessageProps } from '../components/chat/ChatMessage';
import { Conversation } from '../components/chat/ConversationList';
import { MultimodalInput } from '../../api/interfaces/qwen';
import { APIAdapterFactory } from '../../api/adapters';

// 状态接口
interface AppState {
    conversations: Conversation[];
    activeConversationId: string | null;
    messages: Record<string, ChatMessageProps[]>;
    isLoading: boolean;
    error: string | null;
    apiKey: string | null;
}

// 初始状态
const initialState: AppState = {
    conversations: [],
    activeConversationId: null,
    messages: {},
    isLoading: false,
    error: null,
    apiKey: null
};

// 定义Action类型
type Action =
    | { type: 'SET_API_KEY'; payload: string }
    | { type: 'SET_CONVERSATIONS'; payload: Conversation[] }
    | { type: 'ADD_CONVERSATION'; payload: Conversation }
    | { type: 'SET_ACTIVE_CONVERSATION'; payload: string }
    | { type: 'SET_MESSAGES'; payload: { conversationId: string; messages: ChatMessageProps[] } }
    | { type: 'ADD_MESSAGE'; payload: { conversationId: string; message: ChatMessageProps } }
    | { type: 'SET_LOADING'; payload: boolean }
    | { type: 'SET_ERROR'; payload: string | null };

// Reducer
const appReducer = (state: AppState, action: Action): AppState => {
    switch (action.type) {
        case 'SET_API_KEY':
            return {
                ...state,
                apiKey: action.payload
            };
        case 'SET_CONVERSATIONS':
            return {
                ...state,
                conversations: action.payload
            };
        case 'ADD_CONVERSATION':
            return {
                ...state,
                conversations: [action.payload, ...state.conversations]
            };
        case 'SET_ACTIVE_CONVERSATION':
            return {
                ...state,
                activeConversationId: action.payload
            };
        case 'SET_MESSAGES':
            return {
                ...state,
                messages: {
                    ...state.messages,
                    [action.payload.conversationId]: action.payload.messages
                }
            };
        case 'ADD_MESSAGE':
            return {
                ...state,
                messages: {
                    ...state.messages,
                    [action.payload.conversationId]: [
                        ...(state.messages[action.payload.conversationId] || []),
                        action.payload.message
                    ]
                }
            };
        case 'SET_LOADING':
            return {
                ...state,
                isLoading: action.payload
            };
        case 'SET_ERROR':
            return {
                ...state,
                error: action.payload
            };
        default:
            return state;
    }
};

// 创建Context
interface AppContextType {
    state: AppState;
    dispatch: React.Dispatch<Action>;
    sendMessage: (input: MultimodalInput) => Promise<void>;
    createNewConversation: () => void;
    selectConversation: (conversationId: string) => void;
}

const AppContext = createContext<AppContextType | undefined>(undefined);

// Provider组件
interface AppProviderProps {
    children: ReactNode;
}

export const AppProvider: React.FC<AppProviderProps> = ({ children }) => {
    const [state, dispatch] = useReducer(appReducer, initialState);

    // 从本地存储加载状态
    useEffect(() => {
        const loadState = async () => {
            try {
                // 在实际应用中应该使用AsyncStorage或其他存储方式
                const savedApiKey = localStorage.getItem('apiKey');
                const savedConversations = localStorage.getItem('conversations');
                const savedMessages = localStorage.getItem('messages');
                const savedActiveConversationId = localStorage.getItem('activeConversationId');

                if (savedApiKey) {
                    dispatch({ type: 'SET_API_KEY', payload: savedApiKey });
                }

                if (savedConversations) {
                    dispatch({
                        type: 'SET_CONVERSATIONS',
                        payload: JSON.parse(savedConversations)
                    });
                }

                if (savedMessages) {
                    const messages = JSON.parse(savedMessages);
                    Object.keys(messages).forEach(conversationId => {
                        dispatch({
                            type: 'SET_MESSAGES',
                            payload: {
                                conversationId,
                                messages: messages[conversationId].map((msg: any) => ({
                                    ...msg,
                                    timestamp: new Date(msg.timestamp) // 转换时间戳
                                }))
                            }
                        });
                    });
                }

                if (savedActiveConversationId) {
                    dispatch({
                        type: 'SET_ACTIVE_CONVERSATION',
                        payload: savedActiveConversationId
                    });
                }
            } catch (error) {
                console.error('加载状态失败:', error);
            }
        };

        loadState();
    }, []);

    // 保存状态到本地存储
    useEffect(() => {
        const saveState = () => {
            try {
                if (state.apiKey) {
                    localStorage.setItem('apiKey', state.apiKey);
                }

                localStorage.setItem('conversations', JSON.stringify(state.conversations));
                localStorage.setItem('messages', JSON.stringify(state.messages));

                if (state.activeConversationId) {
                    localStorage.setItem('activeConversationId', state.activeConversationId);
                }
            } catch (error) {
                console.error('保存状态失败:', error);
            }
        };

        saveState();
    }, [state]);

    // 发送消息
    const sendMessage = async (input: MultimodalInput) => {
        if (!state.apiKey) {
            dispatch({ type: 'SET_ERROR', payload: '请先设置API密钥' });
            return;
        }

        if (!state.activeConversationId) {
            dispatch({ type: 'SET_ERROR', payload: '请先选择或创建对话' });
            return;
        }

        dispatch({ type: 'SET_LOADING', payload: true });
        dispatch({ type: 'SET_ERROR', payload: null });

        try {
            // 创建用户消息
            const userMessage: ChatMessageProps = {
                id: Date.now().toString(),
                role: 'user',
                content: input.text || '',
                images: input.images || [],
                timestamp: new Date()
            };

            // 添加用户消息
            dispatch({
                type: 'ADD_MESSAGE',
                payload: {
                    conversationId: state.activeConversationId,
                    message: userMessage
                }
            });

            // 创建API适配器
            const adapter = APIAdapterFactory.createAdapter('qwen', state.apiKey);

            // 获取之前的消息
            const previousMessages = state.messages[state.activeConversationId] || [];

            // 构建API请求所需的上下文
            const apiMessages = previousMessages.map(msg => ({
                role: msg.role,
                content: msg.content
            }));

            // 创建临时助手消息（加载中）
            const pendingAssistantMessage: ChatMessageProps = {
                id: (Date.now() + 1).toString(),
                role: 'assistant',
                content: '',
                timestamp: new Date(),
                isLoading: true
            };

            dispatch({
                type: 'ADD_MESSAGE',
                payload: {
                    conversationId: state.activeConversationId,
                    message: pendingAssistantMessage
                }
            });

            // 发送请求
            let responseText = '';

            await adapter.handleMultimodalRequest(
                input,
                {
                    onTextUpdate: (text) => {
                        responseText = text;
                    },
                    onImageUpdate: (imageUrl) => {
                        // 处理图像响应
                        console.log('收到图像:', imageUrl);
                    },
                    onComplete: () => {
                        // 移除加载中消息，添加完成的消息
                        const updatedMessages = [...state.messages[state.activeConversationId]];
                        const pendingIndex = updatedMessages.findIndex(
                            msg => msg.id === pendingAssistantMessage.id
                        );

                        if (pendingIndex !== -1) {
                            updatedMessages.splice(pendingIndex, 1);

                            const assistantMessage: ChatMessageProps = {
                                id: pendingAssistantMessage.id,
                                role: 'assistant',
                                content: responseText,
                                timestamp: new Date(),
                                isLoading: false
                            };

                            dispatch({
                                type: 'SET_MESSAGES',
                                payload: {
                                    conversationId: state.activeConversationId,
                                    messages: [...updatedMessages, assistantMessage]
                                }
                            });

                            // 更新会话标题
                            if (state.conversations.length === 1 && !state.conversations[0].title) {
                                const newTitle = input.text?.substring(0, 20) || '新对话';
                                const updatedConversation = {
                                    ...state.conversations[0],
                                    title: newTitle,
                                    lastMessage: responseText.substring(0, 30),
                                    timestamp: new Date()
                                };

                                dispatch({
                                    type: 'SET_CONVERSATIONS',
                                    payload: [updatedConversation]
                                });
                            } else {
                                const updatedConversations = state.conversations.map(conv => {
                                    if (conv.id === state.activeConversationId) {
                                        return {
                                            ...conv,
                                            lastMessage: responseText.substring(0, 30),
                                            timestamp: new Date()
                                        };
                                    }
                                    return conv;
                                });

                                dispatch({
                                    type: 'SET_CONVERSATIONS',
                                    payload: updatedConversations
                                });
                            }
                        }
                    },
                    onError: (error) => {
                        // 处理错误
                        dispatch({ type: 'SET_ERROR', payload: error.message });

                        // 更新加载中消息为错误状态
                        const updatedMessages = state.messages[state.activeConversationId].map(msg => {
                            if (msg.id === pendingAssistantMessage.id) {
                                return {
                                    ...msg,
                                    isLoading: false,
                                    isError: true,
                                    content: '消息发送失败'
                                };
                            }
                            return msg;
                        });

                        dispatch({
                            type: 'SET_MESSAGES',
                            payload: {
                                conversationId: state.activeConversationId,
                                messages: updatedMessages
                            }
                        });
                    }
                }
            );
        } catch (error) {
            const errorMessage = error instanceof Error ? error.message : '发送消息失败';
            dispatch({ type: 'SET_ERROR', payload: errorMessage });
        } finally {
            dispatch({ type: 'SET_LOADING', payload: false });
        }
    };

    // 创建新会话
    const createNewConversation = () => {
        const newConversation: Conversation = {
            id: Date.now().toString(),
            title: '新对话',
            lastMessage: '',
            timestamp: new Date()
        };

        dispatch({ type: 'ADD_CONVERSATION', payload: newConversation });
        dispatch({ type: 'SET_ACTIVE_CONVERSATION', payload: newConversation.id });
        dispatch({
            type: 'SET_MESSAGES',
            payload: { conversationId: newConversation.id, messages: [] }
        });
    };

    // 选择会话
    const selectConversation = (conversationId: string) => {
        dispatch({ type: 'SET_ACTIVE_CONVERSATION', payload: conversationId });
    };

    return (
        <AppContext.Provider
            value={{
                state,
                dispatch,
                sendMessage,
                createNewConversation,
                selectConversation
            }}
        >
            {children}
        </AppContext.Provider>
    );
};

// 自定义Hook
export const useAppContext = () => {
    const context = useContext(AppContext);
    if (context === undefined) {
        throw new Error('useAppContext必须在AppProvider内部使用');
    }
    return context;
}; 